#include "MyString.h"
#include <iostream>
using namespace std;
#include <cstring>
#include <cstdlib>

ostream& operator << (ostream& out, const MyString& rhs)
{
	out << rhs.m_data;
	return out;
}

MyString::MyString(const char* _str)
{
	if(0 == _str){
		this->m_data = new char[1]();
		this->m_data[0] = '\0';
	}else{
		int len = strlen(_str);
		this->m_data = new char[len + 1]();
		strcpy(this->m_data, _str);
		this->m_data[len] = '\0';
	}

	cout << "MyString" << endl;
}

MyString::~MyString()
{
	if(this->m_data != 0)
		delete [] this->m_data;
	cout << "~MyString" << endl;
}

MyString::MyString(const MyString& rhs)
{
	cout << "copy" << endl;
	//根据rhs申请空间
	int len = strlen(rhs.m_data);
	this->m_data = new char[len + 1]();
	strcpy(this->m_data, rhs.m_data);
	this->m_data[len] = '\0';
}
/*
	一个类有一个默认的赋值运算符重载函数, 默认的实现是将一个对象的所有成员以
	值的形式赋值给另一个对象
*/
const MyString& MyString::operator = (const MyString& rhs)
{
	cout << "operator = " << endl;
	//防止自我赋值
	if(this == &rhs)
		return *this;
	
	//释放原来的空间
	if(this->m_data)
		delete [] this->m_data;
	
	//申请新空间
	int len = strlen(rhs.m_data);
	this->m_data = new char[len + 1]();
	
	//拷贝字符串的值
	strcpy(this->m_data, rhs.m_data);

	return *this;
}

const MyString MyString::operator + (const MyString& rhs) const
{
	//申请一个新空间用来保存拼接后的字符串
	int len = strlen(this->m_data) + strlen(rhs.m_data);
	char *_data = new char[len + 1]();
	//拼接
	strcpy(_data, this->m_data);
	strcat(_data, rhs.m_data);
	
	MyString tmp(_data);
	delete[] _data;
	return tmp;
}

MyString& MyString::operator += (const MyString& rhs)
{
	//申请一个新空间用来保存拼接后的字符串
	int len = strlen(this->m_data) + strlen(rhs.m_data);
	char *_data = new char[len + 1]();
	//拼接
	strcpy(_data, this->m_data);
	strcat(_data, rhs.m_data);
	
	//释放原来的的空间
	if(this->m_data)
		delete[] this->m_data;
	
	//当前对象指向新空间
	this->m_data = _data;
	return *this;
	//*this = *this + rhs;
	//return *this;
}
